package com.chaoyong.higo.activity;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chaoyong.higo.R;
import com.chaoyong.higo.base.BaseActivity;
import com.chaoyong.higo.base.BaseApp;
import com.chaoyong.higo.bean.LoginBean;
import com.chaoyong.higo.net.OApi;
import com.chaoyong.higo.utils.AtyManager;
import com.chaoyong.higo.utils.EmptyUtil;
import com.chaoyong.higo.utils.JLog;
import com.chaoyong.higo.utils.PrefUtils;
import com.chaoyong.higo.utils.StringUtils;
import com.chaoyong.higo.utils.Util;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

/**
 * 登录
 * 
 * @author zk
 *
 */
public class LoginActivity extends BaseActivity {

	private static final String ClassName = LoginActivity.class.getName();

	private Activity context;
	
	private LinearLayout base_left_iv;// 左侧返回按钮
	private TextView base_title_tv;// 标题
	private TextView base_right_tv;// 标题右侧文字
	
	private TextView forget,newreg;

	/** 手机号 */
	private EditText login_phone;
	/** 密码 */
	private EditText login_pwd;
	/** 登录按钮 */
	private Button login_btn;
	/** 立即注册 */
	private TextView login_reg;
	/** QQ登录 */
	private ImageView qq_login,wx_login;

	private String ph = "";
	private String pw = "";
	
	private int isFrom = 0;

	private static Tencent mTencent;
	 private UserInfo mInfo;
	 
	 public static String openidString;
     public static String nicknameString;
     
     Bitmap bitmap = null;
     
     private UMShareAPI mShareAPI;
	
	private static boolean isServerSideLogin = false;

	/*private BaseUiListener listener = new BaseUiListener() {
		
		@Override
		public void onError(UiError arg0) {
			// TODO Auto-generated method stub
			showToast("错误！" + arg0.errorDetail);
		}
		
		@Override
		public void onComplete(Object arg0) {
			// TODO Auto-generated method stub
			showToast("OK！！！！！！！" + arg0.toString());
		}
		
		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			showToast("cancel");
		}
	};*/
	private final static String APP_ID = "1105451502"; 

	@Override
	public int layoutResID() {
		return R.layout.activity_login;
	}

	@Override
	public void findView() {
		findTitleIds();

		context = this;
		mShareAPI = UMShareAPI.get(this);
		mTencent = Tencent.createInstance(APP_ID, context);

		login_phone = (EditText) findViewById(R.id.login_phone);
		login_pwd = (EditText) findViewById(R.id.login_pwd);
		login_btn = (Button) findViewById(R.id.login_btn);
		login_reg = (TextView) findViewById(R.id.login_reg);
		qq_login = (ImageView) findViewById(R.id.qq_login);
		wx_login = (ImageView) findViewById(R.id.wx_login);
		
		forget = (TextView) findViewById(R.id.login_forget_pwd);
		newreg = (TextView) findViewById(R.id.login_register);
		
		/*listener = new BaseUiListener() {
			
			@Override
			public void onError(UiError arg0) {
				// TODO Auto-generated method stub
				showToast("错误！" + arg0.errorDetail);
			}
			
			@Override
			public void onComplete(Object arg0) {
				// TODO Auto-generated method stub
				showToast("OK！！！！！！！" + arg0.toString());
			}
			
			@Override
			public void onCancel() {
				// TODO Auto-generated method stub
				showToast("cancel");
			}
		};*/
	}

	@Override
	public void init() {
		AtyManager.getAtyManager().addActivity(LoginActivity.this);
isFrom = getIntent().getIntExtra("isFrom", 0);
		base_left_iv.setOnClickListener(this);
		base_right_tv.setOnClickListener(this);

		login_btn.setOnClickListener(this);
		login_reg.setVisibility(View.INVISIBLE);
		login_reg.setOnClickListener(this);
		qq_login.setOnClickListener(this);
		wx_login.setOnClickListener(this);

		ph = getIntent().getStringExtra("ph");
		pw = getIntent().getStringExtra("pw");
		if (!StringUtils.isEmpty(ph) && !StringUtils.isEmpty(pw)) {
			login_phone.setText(ph);
			login_pwd.setText(pw);
		}
		/**
		 * 自动登录，判断"isLogin",该字段在用户登录成功之后保存
		 */
		// if (PrefUtils.getBoolean(LoginActivity.this, "isLogin", false)) {
		// Intent login = new Intent(LoginActivity.this, MainActivity.class);
		// startActivity(login);
		// AtyManager.getAtyManager().finishActivity(LoginActivity.this);
		// }

		login_phone.setText(PrefUtils.getString(LoginActivity.this, "userName", ""));
		login_pwd.setText(PrefUtils.getString(LoginActivity.this, "userPwd", ""));
		
		forget.setOnClickListener(this);
		newreg.setOnClickListener(this);

		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.base_left_iv:// 返回
			this.finish();
			overridePendingTransition(R.anim.slide_in_from_top, R.anim.slide_out_to_bottom); 
			break;
		case R.id.base_right_tv:// 注册
		case R.id.login_reg:// 注册
			startActivity(new Intent(this, RegisterActivity.class));
			break;
		case R.id.login_btn:// 登录
			if (beforeCommit()) {
				return;
			} else {
				httpLogin(getText(login_phone), getText(login_pwd));
			}
			break;
		case R.id.qq_login:// QQ登录
			showToast("QQ登录");
			//login();
			//onClickLogin();
			qqLogin();
			break;
		case R.id.wx_login:
			showToast("微信登录");
			
			/*BaseApp.iwxapi = WXAPIFactory.createWXAPI(this, APP_ID, true);
			BaseApp.iwxapi.registerApp(APP_ID);*/
			SendAuth.Req req = new SendAuth.Req();
			req.scope = "snsapi_userinfo";
		    req.state = "wechat_sdk_demo_test";
		    BaseApp.iwxapi.sendReq(req);
			
			break;
		case R.id.login_forget_pwd:
			startActivity(new Intent(this, FrogetPwdActivity.class));
			break;
		case R.id.login_register:
			startActivity(new Intent(this, RegisterActivity.class));
			break;
		}
	}

	 private void qqLogin() {
		// TODO Auto-generated method stub
		final SHARE_MEDIA platform = SHARE_MEDIA.QQ;
		mShareAPI.doOauthVerify(context, platform, new UMAuthListener() {
			
			@Override
			public void onError(SHARE_MEDIA arg0, int arg1, Throwable arg2) {
				// TODO Auto-generated method stub
				showToast("error");
			}
			
			@Override
			public void onComplete(SHARE_MEDIA arg0, int arg1, Map<String, String> arg2) {
				// TODO Auto-generated method stub
				//showToast(arg1 + "===" + arg2.toString());
				mShareAPI.getPlatformInfo(context, platform, new UMAuthListener() {
					
					@Override
					public void onError(SHARE_MEDIA arg0, int arg1, Throwable arg2) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onComplete(SHARE_MEDIA arg0, int arg1, Map<String, String> arg2) {
						// TODO Auto-generated method stub
						//showToast(arg1 + "===" + arg2.toString());
						JSONObject json = new JSONObject();
						final String nickname = arg2.get("screen_name");
						try {
							json.put("unionid", arg2.get("openid"));
							json.put("nickname", nickname);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						RequestParams params = new RequestParams();
						try {
							params.setBodyEntity(new StringEntity(json.toString(), "utf-8"));
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						HttpUtils utils = new HttpUtils();
						utils.send(HttpMethod.POST, OApi.Public_wxLogin, params, new RequestCallBack<String>() {

							@Override
							public void onFailure(HttpException arg0,
									String arg1) {
								// TODO Auto-generated method stub
								
							}

							@Override
							public void onSuccess(ResponseInfo<String> arg0) {
								// TODO Auto-generated method stub
								String results = arg0.result;
								//Toast.makeText(context, results, 1).show();
								try {
									JSONObject jsonObject = new JSONObject(results);
									JSONObject data = jsonObject.getJSONObject("data");
									String uid = data.getString("uid");
									if(jsonObject.getInt("status") == 1){
										//Toast.makeText(context, "已经注册过了，可以直接登录了", 1).show();
										OApi.uid = uid;
										PrefUtils.setBoolean(context, "isLogin", true);
										PrefUtils.setString(context, "userId", uid);
										PrefUtils.setString(context, "userName", nickname);
										startActivity(new Intent(context, MainActivity.class));
										context.finish();
									}
									if(jsonObject.getInt("status") == 2){
										//Toast.makeText(context, "没有注册过，去注册", 1).show();
										Intent intent = new Intent(context, Login2Activity.class);
										intent.putExtra("uid", uid);
										context.finish();
										startActivity(intent);
									}
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						});
					}
					
					@Override
					public void onCancel(SHARE_MEDIA arg0, int arg1) {
						// TODO Auto-generated method stub
						
					}
				});
			}
			
			@Override
			public void onCancel(SHARE_MEDIA arg0, int arg1) {
				// TODO Auto-generated method stub
				showToast("cancel");
			}
		});
	}
	 
	 
	 @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		 super.onActivityResult(requestCode, resultCode, data);
	        mShareAPI.onActivityResult(requestCode, resultCode, data);
	}
	 

	/*public void login(){
	        mTencent.login(LoginActivity.this, "all", listener);
	    }*/
	
	private void findTitleIds() {
		base_left_iv = (LinearLayout) findViewById(R.id.base_left_iv);
		base_title_tv = (TextView) findViewById(R.id.base_title_tv);
		base_right_tv = (TextView) findViewById(R.id.base_right_tv);

		base_title_tv.setText("登录");
		base_right_tv.setText("注册");
	}

	/**
	 * 获取editText输入的内容
	 * 
	 * @param et
	 * @return
	 */
	private String getText(EditText et) {
		return et.getText().toString().trim();
	}

	/**
	 * 检查输入是否为空
	 * 
	 * @return
	 */
	private boolean beforeCommit() {
		if (EmptyUtil.isEmpty(getText(login_phone))) {
			login_phone.setError("手机号不能为空", getResources().getDrawable(R.color.back_color));
			login_phone.requestFocus();
			return true;
		}

		if (EmptyUtil.isEmpty(getText(login_pwd))) {
			login_pwd.setError("密码不能为空");
			login_pwd.requestFocus();
			return true;
		}
		return false;
	}

	/**
	 * 登录接口
	 * 
	 * @param phone
	 *            手机号
	 * @param pwd
	 *            密码
	 */
	private void httpLogin(String phone, String pwd) {
		HttpUtils utils = new HttpUtils();
		RequestParams param = new RequestParams();
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.putOpt("username", phone);
			jsonObject.putOpt("password", pwd);
			// 这俩货是默认值
			jsonObject.putOpt("model", "Members");
			jsonObject.putOpt("function", "appLogin");
			param.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		utils.send(HttpMethod.POST, OApi.Public_appLogin, param, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				JLog.i(ClassName, arg0.getMessage());
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				//JLog.i(ClassName, arg0.result);

				String statue;
				try {
					JSONObject jsonObject = new JSONObject(arg0.result);
					statue = jsonObject.getString("status");
					if (statue.equals("1")) {
						Gson gson = new Gson();
						LoginBean loBean = gson.fromJson(arg0.result, LoginBean.class);

						String id = loBean.getData().getId();
						OApi.uid = id;
						PrefUtils.setBoolean(LoginActivity.this, "isLogin", true);
						PrefUtils.setString(LoginActivity.this, "userId", id);

						if (isFrom == 0) {
							Intent login = new Intent(LoginActivity.this, MainActivity.class);
							startActivity(login);
							AtyManager.getAtyManager().finishActivity(LoginActivity.this);
							/*if (LoginActivity.this instanceof SetClickListener) {
								((SetClickListener) LoginActivity.this).onUser();
							}*/
						}else if(isFrom == 1){
							LoginActivity.this.finish();
							AtyManager.getAtyManager().finishActivity(LoginActivity.this);
						}

						PrefUtils.setString(LoginActivity.this, "userName", getText(login_phone));
						PrefUtils.setString(LoginActivity.this, "userPhone", getText(login_phone));
						PrefUtils.setString(LoginActivity.this, "userPwd", getText(login_pwd));
					} else if (statue.equals("0")) {
						//showToast(jsonObject.getString("message"));
						showToast("用户名或密码错误！");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
		});
	}
	
	/*@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		showToast(arg0 + ":" + arg1 + ":" + arg2);
		if (arg0 == Constants.REQUEST_API) {  
                Tencent.handleResultData(arg2, new BaseUiListener());  
            super.onActivityResult(arg0, arg1, arg2);  
        } 
	}*/
	
	
	
	
	
	
	
	
	
	
	// QQ登录
	
	private void onClickLogin() {
		// TODO Auto-generated method stub
		mTencent.login(context, "all", new BaseUiListener());
		
	}
	
	
	/**当自定义的监听器实现IUiListener接口后，必须要实现接口的三个方法，
     * onComplete  onCancel onError 
     *分别表示第三方登录成功，取消 ，错误。*/
    private class BaseUiListener implements IUiListener {
 
        public void onCancel() {
            // TODO Auto-generated method stub
             //showToast("cancel");
        }
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
            Toast.makeText(context, "登录成功", 0).show();
            try {
                //获得的数据是JSON格式的，获得你想获得的内容
                //如果你不知道你能获得什么，看一下下面的LOG
                //Log.e("chaoyong", "-------------"+response.toString());
                openidString = ((JSONObject) response).getString("openid");
                mTencent.setOpenId(openidString); 
                mTencent.setAccessToken(((JSONObject) response).getString("access_token"), ((JSONObject) response).getString("expires_in")); 
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            /**到此已经获得OpneID以及其他你想获得的内容了
            QQ登录成功了，我们还想获取一些QQ的基本信息，比如昵称，头像什么的，这个时候怎么办？ 
            sdk给我们提供了一个类UserInfo，这个类中封装了QQ用户的一些信息，我么可以通过这个类拿到这些信息 
            如何得到这个UserInfo类呢？  */
            QQToken qqToken = mTencent.getQQToken();
            UserInfo info = new UserInfo(getApplicationContext(), qqToken);
            //这样我们就拿到这个类了，之后的操作就跟上面的一样了，同样是解析JSON           
            info.getUserInfo(new IUiListener() {
 
                public void onComplete(final Object response) {
                    // TODO Auto-generated method stub
                	
                	showToast("ooooooooooookkkkkkkkkkkkkkk");
                	startActivity(new Intent(context, Login2Activity.class));
                    /*Message msg = new Message();
                    msg.obj = response;
                    msg.what = 0;
                    mHandler.sendMessage(msg);
                    //Log.e(TAG, "-----111---"+response.toString());
                    *//**由于图片需要下载所以这里使用了线程，如果是想获得其他文字信息直接
                     * 在mHandler里进行操作
                     * 
                     *//*
                    new Thread(){
 
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            JSONObject json = (JSONObject)response;
                            try {
                                bitmap = Util.getbitmap(json.getString("figureurl_qq_2"));
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            Message msg = new Message();
                            msg.obj = bitmap;
                            msg.what = 1;
                            mHandler.sendMessage(msg);
                        }                       
                    }.start();*/
                }               
                public void onCancel() {
                   // Log.e(TAG, "--------------111112");
                    // TODO Auto-generated method stub                  
                }
                public void onError(UiError arg0) {
                    // TODO Auto-generated method stub
                   // Log.e(TAG, "-111113"+":"+arg0);
                }
                 
            });
             
        }
 
        public void onError(UiError arg0) {
            // TODO Auto-generated method stub
             showToast("error");
        }           
         
    }
	
	
    Handler mHandler = new Handler() {
    	 
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                JSONObject response = (JSONObject) msg.obj;
                if (response.has("nickname")) {
                    try {
                        nicknameString=response.getString("nickname");
                         showToast("nicknameString" + nicknameString);
                         startActivity(new Intent(context, Login2Activity.class));
                        //nicknameTextView.setText(nicknameString);
                        //Log.e(TAG, "--"+nicknameString);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }else if(msg.what == 1){
                Bitmap bitmap = (Bitmap)msg.obj;
                //userlogo.setImageBitmap(bitmap);
                 
            }
        }
 
    };
    
    
	
	// QQ登录
	/*private void onClickLogin() {
		if (!mTencent.isSessionValid()) {
			mTencent.login(this, "all", loginListener);
            isServerSideLogin = false;
			//Log.d("SDKQQAgentPref", "FirstLaunch_SDK:" + SystemClock.elapsedRealtime());
		} else {
            if (isServerSideLogin) { // Server-Side 模式的登陆, 先退出，再进行SSO登陆
                mTencent.logout(this);      
                mTencent.login(this, "all", loginListener);
                isServerSideLogin = false;
                //Log.d("SDKQQAgentPref", "FirstLaunch_SDK:" + SystemClock.elapsedRealtime());
                return;
            }
		    mTencent.logout(this);
			updateUserInfo();
		}
	}
	
	
	IUiListener loginListener = new BaseUiListener() {
        @Override
        protected void doComplete(JSONObject values) {
        	//Log.d("SDKQQAgentPref", "AuthorSwitch_SDK:" + SystemClock.elapsedRealtime());
            initOpenidAndToken(values);
            updateUserInfo();
        }
    };
    
    public static void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
            }
        } catch(Exception e) {
        }
    }
	
    Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				JSONObject response = (JSONObject) msg.obj;
				if (response.has("nickname")) {
					try {
						showToast(response.toString());
						showToast(response.getString("nickname"));
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}else if(msg.what == 1){
				Bitmap bitmap = (Bitmap)msg.obj;
				mUserLogo.setImageBitmap(bitmap);
				mUserLogo.setVisibility(android.view.View.VISIBLE);
			}
		}

	};
    
    private void updateUserInfo() {
		if (mTencent != null && mTencent.isSessionValid()) {
			IUiListener listener = new IUiListener() {

				@Override
				public void onError(UiError e) {

				}

				@Override
				public void onComplete(final Object response) {
					Message msg = new Message();
					msg.obj = response;
					msg.what = 0;
					mHandler.sendMessage(msg);
					new Thread(){

						@Override
						public void run() {
							JSONObject json = (JSONObject)response;
							if(json.has("figureurl")){
								Bitmap bitmap = null;
								try {
									bitmap = com.chaoyong.higo.utils.Util.getbitmap(json.getString("figureurl_qq_2"));
								} catch (JSONException e) {

								}
								Message msg = new Message();
								msg.obj = bitmap;
								msg.what = 1;
								mHandler.sendMessage(msg);
							}
						}

					}.start();
				}

				@Override
				public void onCancel() {

				}
			};
			mInfo = new UserInfo(this, mTencent.getQQToken());
			mInfo.getUserInfo(listener);

		} else {
			mUserInfo.setText("");
			mUserInfo.setVisibility(android.view.View.GONE);
			mUserLogo.setVisibility(android.view.View.GONE);
		}
	}
    
    
    private class BaseUiListener implements IUiListener {

		@Override
		public void onComplete(Object response) {
            if (null == response) {
            	showToast("返回为空,登录失败");
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                showToast("返回为空,登录失败");
                return;
            }
            showToast("登录成功");
            // 有奖分享处理
			doComplete((JSONObject)response);
		}

		protected void doComplete(JSONObject values) {

		}

		@Override
		public void onError(UiError e) {
			showToast("onError: " + e.errorDetail);
		}

		@Override
		public void onCancel() {
			showToast("onCancel");
            if (isServerSideLogin) {
                isServerSideLogin = false;
            }
		}
	}*/
	
}
